package com.ebelter.btlibrary.btble.impl.wristband;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.ebelter.btlibrary.btble.ble.BleManager;
import com.ebelter.btlibrary.btble.ble.bluetooth.callback.ConnectCallback;
import com.ebelter.btlibrary.btble.ble.bluetooth.callback.ScanResultCallback;
import com.ebelter.btlibrary.btble.ble.bluetooth.device.BluetoothUtil;
import com.ebelter.btlibrary.btble.impl.scale.model.ScaleUser;
import com.ebelter.btlibrary.btble.impl.wristband.callback.WristbandResultCallback;
import com.ebelter.btlibrary.btble.impl.wristband.model.SleepResult;
import com.ebelter.btlibrary.btble.impl.wristband.model.StepResult;
import com.ebelter.btlibrary.util.ULog;
import com.yc.pedometer.info.SleepTimeInfo;
import com.yc.pedometer.info.StepOneDayAllInfo;
import com.yc.pedometer.sdk.BLEServiceOperate;
import com.yc.pedometer.sdk.BloodPressureChangeListener;
import com.yc.pedometer.sdk.BluetoothLeService;
import com.yc.pedometer.sdk.DataProcessing;
import com.yc.pedometer.sdk.DeviceScanInterfacer;
import com.yc.pedometer.sdk.ICallback;
import com.yc.pedometer.sdk.ICallbackStatus;
import com.yc.pedometer.sdk.OnServerCallbackListener;
import com.yc.pedometer.sdk.RateChangeListener;
import com.yc.pedometer.sdk.ServiceStatusCallback;
import com.yc.pedometer.sdk.SleepChangeListener;
import com.yc.pedometer.sdk.StepChangeListener;
import com.yc.pedometer.sdk.UTESQLOperate;
import com.yc.pedometer.sdk.WriteCommandToBLE;
import com.yc.pedometer.update.Updates;
import com.yc.pedometer.utils.CalendarUtils;
import com.yc.pedometer.utils.GlobalVariable;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 蓝牙扫描器
 * Created by pan on 2018/1/8 0008.
 */

public class WristbandBle extends BleManager {

    private static final String TAG = "WristbandBle";

    private BLEServiceOperate mBLEServiceOperate;
    private WriteCommandToBLE mWriteCommand;
    private BluetoothLeService mBluetoothLeService;
    private Updates mUpdates;
    private UTESQLOperate mySQLOperate;


    private final int REQUEST_ENABLE_BT = 1;

    private final String testKey1 = "00a4040008A000000333010101000003330101010000333010101000033301010100003330101010000033301010100333010101000033301010100003330101010000333010101000033301010100003330101010000333010101000033301010100003330101010000333010101000033301010100a4040008A0000003330101010000033301010100003330101010000333010101000033301010100000333010101003330101010000333010101000033301010100003330101010000333010101000033301010100003330101010000333010101000033301010100003330101010000333010101";


    private final int UPDATE_STEP_UI_MSG = 0;
    private final int UPDATE_SLEEP_UI_MSG = 1;
    private final int DISCONNECT_MSG = 18;
    private final int CONNECTED_MSG = 19;
    private final int UPDATA_REAL_RATE_MSG = 20;
    private final int RATE_SYNC_FINISH_MSG = 21;
    private final int OPEN_CHANNEL_OK_MSG = 22;
    private final int CLOSE_CHANNEL_OK_MSG = 23;
    private final int TEST_CHANNEL_OK_MSG = 24;
    private final int OFFLINE_SWIM_SYNC_OK_MSG = 25;
    private final int UPDATA_REAL_BLOOD_PRESSURE_MSG = 29;
    private final int OFFLINE_BLOOD_PRESSURE_SYNC_OK_MSG = 30;
    private final int SERVER_CALL_BACK_OK_MSG = 31;
    private final int OFFLINE_SKIP_SYNC_OK_MSG = 32;
    private final int test_mag1 = 35;
    private final int test_mag2 = 36;
    private final int OFFLINE_STEP_SYNC_OK_MSG = 37;
    private final int UPDATE_SPORTS_TIME_DETAILS_MSG = 38;
    private static final int NEW_DAY_MSG = 3;

    private static final int SHOW_SET_PASSWORD_MSG = 26;
    private static final int SHOW_INPUT_PASSWORD_MSG = 27;
    private static final int SHOW_INPUT_PASSWORD_AGAIN_MSG = 28;

    private final int CONNECTED = 1;
    private final int CONNECTING = 2;
    private final int DISCONNECTED = 3;
    private int CURRENT_STATUS = DISCONNECTED;

    private final long TIME_OUT_SERVER = 10000;
    private final long TIME_OUT = 120000;


    private ScanResultCallback mScanResultCallback;
    private ConnectCallback mConnectCallback;
    private WristbandResultCallback mWristbandResultCallback;
    private SimpleDateFormat sdf;
    private int index = 0;

    private static WristbandBle instance = new WristbandBle();

    private WristbandBle() {
    }

    public static WristbandBle getInstance() {
        return instance;
    }

    @Override
    public void registerConnectCallback(ConnectCallback callback) {
        this.mConnectCallback = callback;
    }

    public void registerMeasureResultCallback(WristbandResultCallback callback) {
        this.mWristbandResultCallback = callback;
    }

    @Override
    protected void initBleService(Activity aty) {
        mActivity = aty;

        // 用于BluetoothLeService实例化准备,必须
        mBLEServiceOperate = BLEServiceOperate.getInstance(aty);
        if (!mBLEServiceOperate.isSupportBle4_0()) {
//            Toast.makeText(ctx, "此设备不支持BLE", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "----initBleService-----This device do not support BLE4.0");
            return;
        }
        updateHandler = new MainHandler(mActivity.getMainLooper());

        if (!mBLEServiceOperate.isBleEnabled()) {
            open(mActivity);
        }

        mBLEServiceOperate.setDeviceScanListener(new DeviceScanInterfacer() {
            @Override
            public void LeScanCallback(final BluetoothDevice device, int i) {
                if (!BluetoothUtil.isDeviceNameMatch(device.getName())) {
                    return;
                }
                Log.i(TAG, "----LeScanCallback-----name = " + device.getName() + ", addr = " + device.getAddress());

                //回调
                if (mScanResultCallback != null) {
                    mScanResultCallback.onDiscovered(device);
                }
                curDevice = device;
                //连接设备
                if (curDevice != null) {
                    mBLEServiceOperate.stopLeScan();
                    startConnect(device);
                }


            }
        });

        // for  DeviceScanInterfaceruetoothLeService.setICallback(mICallback);
        mBLEServiceOperate.setServiceStatusCallback(connectStatus);
        // 如果没在搜索界面提前实例BLEServiceOperate的话，下面这4行需要放到OnServiceStatuslt
        mBluetoothLeService = mBLEServiceOperate.getBleService();
        Log.i(TAG, "-------startScan---before---- mBluetoothLeService = " + mBluetoothLeService);
        if (mBluetoothLeService != null) {
            mBluetoothLeService.setICallback(mICallback);
            mBluetoothLeService.setRssiHandler(updateHandler);
        }

        mySQLOperate = UTESQLOperate.getInstance(mActivity);// 2.2.1版本修改
        mUpdates = Updates.getInstance(mActivity);
        mUpdates.setHandler(updateHandler);// 获取升级操作信息
        mWriteCommand = WriteCommandToBLE.getInstance(mActivity);

        mUpdates.registerBroadcastReceiver();
        mUpdates.setOnServerCallbackListener(mOnServerCallbackListener);


        DataProcessing mDataProcessing = DataProcessing.getInstance(mActivity);
        mDataProcessing.setOnStepChangeListener(mOnStepChangeListener);
        mDataProcessing.setOnSleepChangeListener(mOnSleepChangeListener);

//        mDataProcessing.setOnRateListener(mOnRateListener);
//        mDataProcessing.setOnBloodPressureListener(mOnBloodPressureListener);
    }

    @Override
    protected void setBleParams() {

    }

    @Override
    public void startScan(ScanResultCallback callback) {
        this.mScanResultCallback = callback;
        startScan();
    }

    @Override
    public void startScan() {
        Log.i(TAG, "-------startScan------- ");
        mBLEServiceOperate.startLeScan();
    }

    @Override
    public void disConnectDevice() {
        if (mBluetoothLeService != null) {
            mBluetoothLeService.disconnect();
            try {
                mBluetoothLeService.disconnect();
                if (mBLEServiceOperate!=null) {
                    mBLEServiceOperate.disConnect();
                }
            }catch (Exception e){
                ULog.e(TAG, "------disConnectDevice---------e.getMessage() = " + e.getMessage());
            }
        }
    }

    /**
     * 连接设备
     *
     * @param device
     */
    public void startConnect(BluetoothDevice device) {
        Log.i(TAG, "-------startConnect------- device.getAddress() = " + device.getAddress());
        mBLEServiceOperate.connect(device.getAddress());
    }

    public void stopScan() {
        mBLEServiceOperate.stopLeScan();
    }

    /**
     * 设置用户信息
     */
    public void setUserInfo() {
        // 设置步长，体重，灭屏时间5s，目标步数，抬手亮屏开关true为开，false为关；最高心率提醒，true为开，false为关；最后一个参数为最高心率提醒的值
        mWriteCommand.sendStepLenAndWeightToBLE(ScaleUser.getUser().getHeight(), (int) ScaleUser.getUser().getWeight(), 5, 10000, true, true, 150);

    }

    /**
     * 步数数据同步
     */
    public void syncSteps() {
        Log.i(TAG, "-------syncSteps------- ");
        mWriteCommand.syncAllStepData();
    }

    /**
     * 心率数据同步
     */
    public void syncPulse() {
        Log.i(TAG, "-------syncPulse------- ");
        mWriteCommand.syncAllRateData();
    }
    /**
     * 睡眠数据同步
     */
    public void syncSleep(int index) {
        this.index = index;
        Log.i(TAG, "-------syncSleep------- ");
        mWriteCommand.syncAllSleepData();
    }


    private ServiceStatusCallback connectStatus = new ServiceStatusCallback() {
        @Override
        public void OnServiceStatuslt(int status) {
            Log.i(TAG, "----OnServiceStatuslt-----status = " + status);
            if (status == ICallbackStatus.BLE_SERVICE_START_OK) {
                if (mBluetoothLeService == null) {
                    mBluetoothLeService = mBLEServiceOperate.getBleService();
                    mBluetoothLeService.setICallback(mICallback);
                    mBluetoothLeService.setRssiHandler(updateHandler);
                }
            }
        }
    };

    private ICallback mICallback = new ICallback() {
        @Override
        public void OnResult(boolean result, int status) {
            Log.i(TAG, "----OnResult----result=" + result + ",status=" + status);
            switch (status) {
                case ICallbackStatus.OFFLINE_STEP_SYNCING:  // 正在同步数据
                    break;
                case ICallbackStatus.OFFLINE_STEP_SYNC_OK:  //同步步数数据成功
                    Log.i(TAG, "----OnResult-----步数数据同步成功！ ");
                    if (mWristbandResultCallback != null) {
                        mWristbandResultCallback.onReceiveStepFinished();
                    }
                    //紧接着同步睡眠数据
                    syncSleep(0);
                    break;
                case ICallbackStatus.OFFLINE_SLEEP_SYNC_OK:  //同步睡眠数据成功
                    Log.i(TAG, "----OnResult-----睡眠数据同步成功！ ");
                    if (mWristbandResultCallback != null) {
                        mWristbandResultCallback.onReceiveSleepFinished();
                    }
                    break;
                case ICallbackStatus.SYNC_TIME_OK:// (时间在同步在SDK内部已经帮忙同步，你不需要同步时间了，sdk内部同步时间完成会自动回调到这里)
                    Log.i(TAG, "----OnResult-----SYNC_TIME_OK  and  GET_BLE_VERSION .");
                    //同步时间成功后，会回调到这里，延迟20毫秒，获取固件版本
                    // delay 20ms  send
                    // to read
                    // localBleVersion
                    mWriteCommand.sendToReadBLEVersion();
                    break;
                case ICallbackStatus.GET_BLE_VERSION_OK:// 获取固件版本成功后会回调到这里，延迟20毫秒，设置身高体重到手环
                    Log.i(TAG, "----OnResult-----GET_BLE_VERSION_OK  and  syncAllStepData .");
                    // localBleVersion
                    // finish,
                    // then sync
                    // step
                    mWriteCommand.syncAllStepData();
                    break;
                case ICallbackStatus.DISCONNECT_STATUS:
                    if (mConnectCallback != null) {
                        mConnectCallback.onDisConnected();
                    }
                    mConnectStatus = ConnectStatus.DISCONNECTED;
                    break;
                case ICallbackStatus.CONNECTED_STATUS:
                    Log.d(TAG, "----OnResult----CONNECTED_STATUS，连接成功！");
                    if (mConnectCallback != null) {
                        mConnectCallback.onConnected(curDevice);
                    }
                    setUserInfo();
                    mConnectStatus = ConnectStatus.CONNECTED;
                    break;

                case ICallbackStatus.DISCOVERY_DEVICE_SHAKE:
                    Log.d(TAG, "摇一摇拍照");
                    // Discovery device Shake
                    break;
                case ICallbackStatus.OFFLINE_RATE_SYNCING://正在同步心率数据
                    break;
                case ICallbackStatus.OFFLINE_RATE_SYNC_OK:  //  心率数据同步完成
                    if (mWristbandResultCallback != null) {
                        mWristbandResultCallback.onReceivePulseFinished();
                    }
                    break;
                case ICallbackStatus.SET_METRICE_OK: // 设置公制单位成功
                    break;
                case ICallbackStatus.SET_INCH_OK: //// 设置英制单位成功
                    break;
                case ICallbackStatus.SET_FIRST_ALARM_CLOCK_OK: // 设置第1个闹钟OK
                    break;
                case ICallbackStatus.SET_SECOND_ALARM_CLOCK_OK: //设置第2个闹钟OK
                    break;
                case ICallbackStatus.SET_THIRD_ALARM_CLOCK_OK: // 设置第3个闹钟OK
                    break;
                case ICallbackStatus.SEND_PHONE_NAME_NUMBER_OK:
                    mWriteCommand.sendQQWeChatVibrationCommand(5);
                    break;
                case ICallbackStatus.SEND_QQ_WHAT_SMS_CONTENT_OK:
                    mWriteCommand.sendQQWeChatVibrationCommand(1);
                    break;
                case ICallbackStatus.PASSWORD_SET:
                    Log.d(TAG, "没设置过密码，请设置4位数字密码");
//                    mHandler.sendEmptyMessage(SHOW_SET_PASSWORD_MSG);
                    break;
                case ICallbackStatus.PASSWORD_INPUT:
                    Log.d(TAG, "已设置过密码，请输入已设置的4位数字密码");
//                    mHandler.sendEmptyMessage(SHOW_INPUT_PASSWORD_MSG);
                    break;
                case ICallbackStatus.PASSWORD_AUTHENTICATION_OK:
                    Log.d(TAG, "验证成功或者设置密码成功");
                    break;
                case ICallbackStatus.PASSWORD_INPUT_AGAIN:
                    Log.d(TAG, "验证失败或者设置密码失败，请重新输入4位数字密码，如果已设置过密码，请输入已设置的密码");
//                    mHandler.sendEmptyMessage(SHOW_INPUT_PASSWORD_AGAIN_MSG);
                    break;
                case ICallbackStatus.OFFLINE_SWIM_SYNCING:
                    Log.d(TAG, "游泳数据同步中");
                    break;
                case ICallbackStatus.OFFLINE_SWIM_SYNC_OK:
                    Log.d(TAG, "游泳数据同步完成");
//                    mHandler.sendEmptyMessage(OFFLINE_SWIM_SYNC_OK_MSG);
                    break;
                case ICallbackStatus.OFFLINE_BLOOD_PRESSURE_SYNCING:
                    Log.d(TAG, "血压数据同步中");
                    break;
                case ICallbackStatus.OFFLINE_BLOOD_PRESSURE_SYNC_OK:
                    Log.d(TAG, "血压数据同步完成");
//                    mHandler.sendEmptyMessage(OFFLINE_BLOOD_PRESSURE_SYNC_OK_MSG);
                    break;
                case ICallbackStatus.OFFLINE_SKIP_SYNCING:
                    Log.d(TAG, "跳绳数据同步中");
                    break;
                case ICallbackStatus.OFFLINE_SKIP_SYNC_OK:
                    Log.d(TAG, "跳绳数据同步完成");
//                    mHandler.sendEmptyMessage(OFFLINE_SKIP_SYNC_OK_MSG);
                    break;
                case ICallbackStatus.MUSIC_PLAYER_START_OR_STOP:
                    Log.d(TAG, "音乐播放/暂停");
                    break;
                case ICallbackStatus.MUSIC_PLAYER_NEXT_SONG:
                    Log.d(TAG, "音乐下一首");
                    break;
                case ICallbackStatus.MUSIC_PLAYER_LAST_SONG:
                    Log.d(TAG, "音乐上一首");
                    break;
                case ICallbackStatus.OPEN_CAMERA_OK:
                    Log.d(TAG, "打开相机ok");
                    break;
                case ICallbackStatus.CLOSE_CAMERA_OK:
                    Log.d(TAG, "关闭相机ok");
                    break;
                case ICallbackStatus.PRESS_SWITCH_SCREEN_BUTTON:
                    Log.d(TAG, "表示按键1短按下，用来做切换屏,表示切换了手环屏幕");
//                    mHandler.sendEmptyMessage(test_mag1);
                    break;
                case ICallbackStatus.PRESS_END_CALL_BUTTON:
                    Log.d(TAG, "表示按键1长按下，一键拒接来电");
                    break;
                case ICallbackStatus.PRESS_TAKE_PICTURE_BUTTON:
                    Log.d(TAG, "表示按键2短按下，用来做一键拍照");
                    break;
                case ICallbackStatus.PRESS_SOS_BUTTON:
                    Log.d(TAG, "表示按键3短按下，用来做一键SOS");
//                    mHandler.sendEmptyMessage(test_mag2);
                    break;
                case ICallbackStatus.PRESS_FIND_PHONE_BUTTON:
                    Log.d(TAG, "表示按键按下，手环查找手机的功能。");

                    break;
                default:
                    break;
            }
        }

        @Override
        public void OnDataResult(boolean b, int status, byte[] data) {
            Log.i(TAG, "----OnDataResult-----status = " + status);
            StringBuilder stringBuilder = null;
            if (data != null && data.length > 0) {
                stringBuilder = new StringBuilder(data.length);
                for (byte byteChar : data) {
                    stringBuilder.append(String.format("%02X", byteChar));
                }
                Log.i("testChannel", "BLE---->APK data =" + stringBuilder.toString());
            }
            if (status == ICallbackStatus.OPEN_CHANNEL_OK) {// 打开通道OK
//                mHandler.sendEmptyMessage(OPEN_CHANNEL_OK_MSG);

                mWriteCommand.sendAPDUToBLE(WriteCommandToBLE.hexString2Bytes(testKey1));

            } else if (status == ICallbackStatus.CLOSE_CHANNEL_OK) {// 关闭通道OK
//                mHandler.sendEmptyMessage(CLOSE_CHANNEL_OK_MSG);
            } else if (status == ICallbackStatus.BLE_DATA_BACK_OK) {// 测试通道OK，通道正常
//                mHandler.sendEmptyMessage(TEST_CHANNEL_OK_MSG);
                mWriteCommand.closeBLEchannel();
            }
        }

        @Override
        public void onCharacteristicWriteCallback(int i) {
            Log.i(TAG, "----onCharacteristicWriteCallback-----i = " + i);
        }

        @Override
        public void onIbeaconWriteCallback(boolean b, int i, int i1, String s) {
            Log.i(TAG, "----onIbeaconWriteCallback-----i = " + i);
        }

        @Override
        public void onQueryDialModeCallback(boolean b, int i, int i1, int i2) {
            Log.i(TAG, "----onQueryDialModeCallback-----i = " + i);
        }

        @Override
        public void onControlDialCallback(boolean b, int i, int i1) {
            Log.i(TAG, "----onControlDialCallback-----i = " + i);
        }

        @Override
        public void onSportsTimeCallback(boolean b, String s, int i, int i1) {
            Log.i(TAG, "----onSportsTimeCallback-----i = " + i);
        }
    };


    private OnServerCallbackListener mOnServerCallbackListener = new OnServerCallbackListener() {
        @Override
        public void OnServerCallback(int i) {
            Log.i(TAG, "----OnServerCallback-----i = " + i);
        }
    };

    private MainHandler updateHandler;

    private class MainHandler extends Handler {


        public MainHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RATE_SYNC_FINISH_MSG:
//                    UpdateUpdataRateMainUI(CalendarUtils.getCalendar(0));
//                    Toast.makeText(mContext, "Rate sync finish", 0).show();
                    break;
                case UPDATA_REAL_RATE_MSG:
//                    tv_rate.setText(tempRate + "");// 实时跳变
//                    if (tempStatus == GlobalVariable.RATE_TEST_FINISH) {
//                        UpdateUpdataRateMainUI(CalendarUtils.getCalendar(0));
//                        Toast.makeText(mContext, "Rate test finish", 0).show();
//                    }
                    break;
                case GlobalVariable.GET_RSSI_MSG:

                    break;
                case UPDATE_STEP_UI_MSG://步数
//                    updateSteps(mSteps);
//                    updateCalories(mCalories);
//                    updateDistance(mDistance);
//
//                    Log.d("onStepHandler", "mSteps =" + mSteps + ",mDistance ="
//                            + mDistance + ",mCalories =" + mCalories);
                    break;
                case UPDATE_SLEEP_UI_MSG:
//                    querySleepInfo();
                    Log.d("getSleepInfo", "UPDATE_SLEEP_UI_MSG");
                    break;
                case NEW_DAY_MSG:

                    break;
                case GlobalVariable.START_PROGRESS_MSG:
                    Log.i(TAG, "(Boolean) msg.obj=" + (Boolean) msg.obj);

                    break;
                case GlobalVariable.DOWNLOAD_IMG_FAIL_MSG:

                    break;
                case GlobalVariable.DISMISS_UPDATE_BLE_DIALOG_MSG:
                    Log.i(TAG, "(Boolean) msg.obj=" + (Boolean) msg.obj);

                    break;
                case GlobalVariable.SERVER_IS_BUSY_MSG:
                    break;
                case DISCONNECT_MSG:
                    CURRENT_STATUS = DISCONNECTED;

                    if (mConnectCallback != null) {
                        mConnectCallback.onDisConnected();
                    }
                    Log.i(TAG, "---------DISCONNECT_MSG-----------");

                    break;
                case CONNECTED_MSG:

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            while (!Thread.interrupted()) {
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                if (mBluetoothLeService != null) {
                                    mBluetoothLeService.readRssi();
                                }
                            }
                        }
                    }).start();
                    CURRENT_STATUS = CONNECTED;
                    if (mConnectCallback != null) {
                        mConnectCallback.onConnected(curDevice);
                    }
//                    Toast.makeText(mActivity, "connected", Toast.LENGTH_SHORT).show();
                    break;

                case GlobalVariable.UPDATE_BLE_PROGRESS_MSG: // (新) 增加固件升级进度
                    int schedule = msg.arg1;
                    Log.i("zznkey", "schedule =" + schedule);
//
                    break;
                case OPEN_CHANNEL_OK_MSG:// 打开通道OK

                    mWriteCommand.sendAPDUToBLE(WriteCommandToBLE
                            .hexString2Bytes(testKey1));
                    break;
                case CLOSE_CHANNEL_OK_MSG:// 关闭通道OK

                    break;
                case TEST_CHANNEL_OK_MSG:// 通道测试OK

                    mWriteCommand.closeBLEchannel();
                    break;

                case SHOW_SET_PASSWORD_MSG:
                    break;
                case SHOW_INPUT_PASSWORD_MSG:
                    break;
                case SHOW_INPUT_PASSWORD_AGAIN_MSG:
                    break;
                case OFFLINE_SWIM_SYNC_OK_MSG:

                    break;

                case UPDATA_REAL_BLOOD_PRESSURE_MSG:

                    break;
                case OFFLINE_BLOOD_PRESSURE_SYNC_OK_MSG:

                    break;
                case SERVER_CALL_BACK_OK_MSG:

                    break;
                case OFFLINE_SKIP_SYNC_OK_MSG:

                    break;
                case test_mag1:
//                    Toast.makeText(mActivity, "表示按键1短按下，用来做切换屏,表示切换了手环屏幕", Toast.LENGTH_SHORT).show();
//                    show_result.setText("表示按键1短按下，用来做切换屏,表示切换了手环屏幕");
                    break;
                case test_mag2:
//                    Toast.makeText(mActivity, "表示按键3短按下，用来做一键SOS", Toast.LENGTH_SHORT).show();
//                    show_result.setText("表示按键3短按下，用来做一键SOS");
                    break;
                case OFFLINE_STEP_SYNC_OK_MSG:
//                    Toast.makeText(mActivity, "计步数据同步成功", Toast.LENGTH_SHORT).show();
//                    show_result.setText("计步数据同步成功");
                    break;
                case UPDATE_SPORTS_TIME_DETAILS_MSG:
//                    show_result.setText(resultBuilder.toString());
                    break;
                default:
                    break;
            }
        }
    }

    private StepChangeListener mOnStepChangeListener = new StepChangeListener() {
        @Override
        public void onStepChange(StepOneDayAllInfo info) {
            Log.i(TAG, "------------onStepChange---------------info = " + info);
            if (info != null) {

                long measureTime = System.currentTimeMillis();

                int mSteps = info.getStep();
                float mDistance = info.getDistance();
                int mCalories = info.getCalories();
                StepResult result = new StepResult();
                result.setSteps(mSteps);
                result.setDistance(mDistance);
                result.setCalories(mCalories);

                result.setMeasureTime(measureTime);
                result.setMeasureTimeStr(getMeasureTimeStr(measureTime));
                if (mWristbandResultCallback != null) {
                    mWristbandResultCallback.onReceiveStepResult(result);
                }
                int mRunSteps = info.getRunSteps();
                int mRunCalories = info.getRunCalories();
                float mRunDistance = info.getRunDistance();
                int mRunDurationTime = info.getRunDurationTime();

                int mWalkSteps = info.getWalkSteps();
                int mWalkCalories = info.getWalkCalories();
                float mWalkDistance = info.getWalkDistance();
                int mWalkDurationTime = info.getWalkDurationTime();
                Log.i(TAG, "----------onStepChange---------mSteps =" + mSteps + ",mDistance ="
                        + mDistance + ",mCalories =" + mCalories + ",mRunSteps ="
                        + mRunSteps + ",mRunCalories =" + mRunCalories
                        + ",mRunDistance =" + mRunDistance + ",mRunDurationTime ="
                        + mRunDurationTime + ",mWalkSteps =" + mWalkSteps
                        + ",mWalkCalories =" + mWalkCalories + ",mWalkDistance ="
                        + mWalkDistance + ",mWalkDurationTime ="
                        + mWalkDurationTime);

            }


        }
    };


    public String getMeasureTimeStr(long measureTime) {
        if (sdf == null) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
        Date curDate = new Date(measureTime);
        return sdf.format(curDate);
    }


    /**
     * 睡眠监听 在这里更新UI
     */
    private SleepChangeListener mOnSleepChangeListener = new SleepChangeListener() {

        @Override
        public void onSleepChange() {
            Log.i(TAG, "-------onSleepChange-----");
            querySleepInfo(index);
        }

    };

    private RateChangeListener mOnRateListener = new RateChangeListener() {

        @Override
        public void onRateChange(int rate, int status) {
            Log.i(TAG, "-------onRateChange-----rate  =" + rate + ", status = " + status);
            if (mWristbandResultCallback != null) {
                mWristbandResultCallback.onReceivePulse(rate);
            }
        }
    };
    private BloodPressureChangeListener mOnBloodPressureListener = new BloodPressureChangeListener() {

        @Override
        public void onBloodPressureChange(int hightPressure, int lowPressure,
                                          int status) {
            Log.i(TAG, "-------onBloodPressureChange-----hightPressure  =" + hightPressure + ", lowPressure = " + lowPressure + ", status = " + status);

            if (mWristbandResultCallback != null) {
                mWristbandResultCallback.onReceiveBloodPressure(hightPressure, lowPressure);
            }
        }
    };


    /**
     * 获取某一天睡眠详细，并更新睡眠UI CalendarUtils.getCalendar(0)代表今天，也可写成"20141101"
     * CalendarUtils.getCalendar(-1)代表昨天，也可写成"20141031"
     * CalendarUtils.getCalendar(-2)代表前天，也可写成"20141030" 以此类推
     * @param index
     */
    public void querySleepInfo(int index) {

        SleepTimeInfo sleepTimeInfo = mySQLOperate.querySleepInfo(CalendarUtils.getCalendar(index));
        Log.i(TAG, "---------querySleepInfo---------sleepTimeInfo = " + sleepTimeInfo);
        int deepTime, lightTime, awakeCount, sleepTotalTime;
        if (sleepTimeInfo != null) {
            deepTime = sleepTimeInfo.getDeepTime();
            lightTime = sleepTimeInfo.getLightTime();
            awakeCount = sleepTimeInfo.getAwakeCount();
            sleepTotalTime = sleepTimeInfo.getSleepTotalTime();

            int[] colorArray = sleepTimeInfo.getSleepStatueArray();// 绘图中不同睡眠状态可用不同颜色表示，颜色自定义
            int[] timeArray = sleepTimeInfo.getDurationTimeArray();
            int[] timePointArray = sleepTimeInfo.getTimePointArray();

            Log.i(TAG, "--------querySleepInfo---------Calendar=" + CalendarUtils.getCalendar(0)
                    + ",timeArray =" + timeArray + ",timeArray.length ="
                    + timeArray.length + ",colorArray =" + colorArray
                    + ",colorArray.length =" + colorArray.length
                    + ",timePointArray =" + timePointArray
                    + ",timePointArray.length =" + timePointArray.length);

            long measureTime = System.currentTimeMillis();


            float total_hour = ((float) sleepTotalTime / 60f);
            int deep_hour = deepTime / 60;
            int deep_minute = (deepTime - deep_hour * 60);
            int light_hour = lightTime / 60;
            int light_minute = (lightTime - light_hour * 60);
            int active_count = awakeCount;

            SleepResult result = new SleepResult();
            result.setTotalHour(total_hour);
            result.setDeepHour(deep_hour);
            result.setDeepMinute(deep_minute);
            result.setLightHour(light_hour);
            result.setLightMinute(light_minute);
            result.setActiveCount(active_count);


            result.setMeasureTime(measureTime);
            result.setMeasureTimeStr(getMeasureTimeStr(measureTime));

            if (mWristbandResultCallback!=null){
                mWristbandResultCallback.onReceiveSleep(result);
            }

        } else {
            Log.i(TAG, "------getSleepInfo--------sleepTimeInfo =" + sleepTimeInfo);
            if (mWristbandResultCallback!=null){
                mWristbandResultCallback.onReceiveSleep(null);
            }
        }
    }


    @Override
    public void release() {
        super.release();
        ULog.i(TAG, "--------release-------");
        if (mUpdates != null) {
            mUpdates.clearUpdateSetting();
            mUpdates = null;
        }

        try {

            if (mBluetoothLeService != null) {
                mBluetoothLeService.disconnect();
                mBluetoothLeService.onDestroy();
                mBluetoothLeService = null;

            }
            if (mBLEServiceOperate != null) {
                mBLEServiceOperate.stopLeScan();
                mBLEServiceOperate.disConnect();
                mBLEServiceOperate.unBindService();
                mBLEServiceOperate = null;
            }
            if (mWriteCommand != null) {
                mWriteCommand.closeBLEchannel();
                mWriteCommand = null;
            }
        }catch (Exception e){
            ULog.i(TAG, "---------release---------e.getMessage() = " + e.getMessage());
        }
        mWristbandResultCallback = null;
        mScanResultCallback = null;
        mConnectCallback = null;
        mICallback = null;

    }
}
